import os
import cv2
import arrow
import smtplib
import requests
import numpy as np
import configparser
from email.mime.text import MIMEText
from PIL import ImageFont, ImageDraw, Image
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


conf = configparser.ConfigParser()
root = './config.ini'
conf.read(root, encoding='gbk')

motions = {}
motions_day = {}

to_email, name, sex, age, password, my_email = [None for i in range(6)]


# 初始化数据
def init():
    global to_email, name, sex, age, password, my_email

    to_email = conf.get('setting', 'to-email')
    my_email = conf.get('setting', 'my-email')
    name = conf.get('user-info', 'name')
    sex = conf.get('user-info', 'sex')
    age = conf.get('user-info', 'age')
    password = conf.get('setting', 'password')

    for i in conf.options('motions'):
        motions[i] = conf.get('motions', i)

    for i in conf.options('motions-day'):
        motions_day[i] = conf.get('motions-day', i)


# 获取用户选择的任务,天数,数量
def get_mission():
    print('任务清单:', *motions)
    flag_name = input("请输入任务名称进行打卡:")
    day = motions_day[flag_name]
    num = motions[flag_name]

    print("您{0}打卡的天数为:{1}".format(flag_name, day))
    print("您{0}上次打卡数量为:{1}".format(flag_name, num))
    message = input("请输入打卡数量:")

    to_be_nums = str(int(message) + int(num))

    conf.set('motions', flag_name, to_be_nums)
    conf.set('motions-day', flag_name, str(int(day) + 1))
    conf.write(open(root, "w"))
    print("打卡成功!")

    # 任务 数量 天数
    return flag_name, to_be_nums, int(day) + 1


def parse():
    yd_url = "https://dict.youdao.com/infoline?mode=publish&date=" + arrow.now().format(
        'YYYY-MM-DD') + "&update=auto&apiversion=5.0"
    for record in requests.get(yd_url).json()[arrow.now().format('YYYY-MM-DD')]:
        if record['type'] == '壹句':
            content = record['title']
            translation = record['summary']
            break

    return content, translation


def image(thing, num, day):
    s1, s2 = parse()
    # 编辑图片路径
    bk_img = cv2.imread("wallpaper.jpg")
    # 设置需要显示的字体
    fontpath = "simhei.ttf"
    # 32为字体大小
    font = ImageFont.truetype(fontpath, 50)
    img_pil = Image.fromarray(bk_img)
    draw = ImageDraw.Draw(img_pil)
    # 绘制文字信息
    # (100,300/350)为字体的位置，(255,255,255)为白色，(0,0,0)为黑色
    # -------------------字符处理--------------------------

    str2 = list(s1)
    str2.insert(42, "\n")
    text1 = "".join(str2)

    str5 = list(s2)
    str5.insert(21, "\n")
    text2 = "".join(str5)

    draw.text((0, 0), thing, font=ImageFont.truetype(fontpath, 28), fill=(255, 255, 255), troke_width=1)
    # pil中的颜色是BGR而不是RGB
    draw.text((350, 200), "坚持打卡天数", font=ImageFont.truetype(fontpath, 70), fill=(193, 182, 255), stroke_width=1)
    draw.text((460, 290), "%2d天" % (day), font=ImageFont.truetype(fontpath, 70), fill=(193, 182, 255), stroke_width=1)

    draw.text((0, 1700), text1, font=font, fill=(255, 255, 255))
    # y轴间隔100坐标,50个坐标换一行
    draw.text((0, 1800), text2, font=font, fill=(255, 255, 255))

    draw.text((800, 1630), f"加好友一起{thing}", font=ImageFont.truetype(fontpath, 28), fill=(255, 255, 255))
    draw.text((0, 1600), f"{thing}累计打卡数量:{num}个", font=ImageFont.truetype(fontpath, 50), fill=(193, 255, 193))

    img1 = Image.open("./imgserver.jpg")
    img_pil.paste(img1, (800, 1350))

    bk_img = np.array(img_pil)

    # 保存图片路径
    cv2.imwrite("new_img.jpg", bk_img)
    os.startfile("new_img.jpg")

    # os.system(r'del C:\Users\Administrator\Desktop\new_img.jpg')


def send():
    _to = to_email
    _user = my_email
    _pwd = password

    # 如名字所示Multipart就是分多个部分
    msg = MIMEMultipart()
    msg["Subject"] = "恭喜您离目标又近了一步！"
    msg["From"] = _user
    msg["To"] = _to

    # ---这是文字部分---
    part = MIMEText("恭喜打卡成功！")
    msg.attach(part)

    # jpg类型附件
    part = MIMEApplication(open('new_img.jpg', 'rb').read())
    part.add_header('Content-Disposition', 'attachment', filename="每日打卡.jpg")
    msg.attach(part)

    smtp = smtplib.SMTP_SSL("smtp.qq.com", 465)

    # HELO 向服务器标识用户身份
    smtp.helo("smtp.qq.com")
    # 服务器返回结果确认
    smtp.ehlo("smtp.qq.com")
    # 登录邮箱服务器用户名和密码
    smtp.login(_user, _pwd)
    print("Start send email...")
    smtp.sendmail(_user, _to, msg.as_string())
    smtp.quit()
    print("发送成功！")


if __name__ == "__main__":
    init()
    flag, num, day = get_mission()
    image(flag, num, day)
    send()
